package com.example.message;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@SpringBootApplication
public class MessageMappingApplication {

	public static void main(String[] args) {
		SpringApplication.run(MessageMappingApplication.class, args);
	}

	@SpringBootConfiguration
	@EnableWebSocket
	public class WebSocketConfig implements WebSocketConfigurer {

		@Override
		public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
			registry.addHandler(chatWebSocketHandler(), "/chat/{roomId}").setAllowedOrigins("*");
		}

		@Bean
		public WebSocketHandler chatWebSocketHandler() {
			return new ChatWebSocketHandler();
		}
	}

	@Controller
	public class WebSocketController {

		@MessageMapping("/chat/{roomId}")
		@SendTo("/topic/chat/{roomId}")
		public ChatMessage handleChatMessage(@DestinationVariable String roomId, ChatMessage message) {
			return message;
		}
	}

	public class ChatMessage {
		private String content;
		private String sender;

		// getters and setters
	}

	public class ChatWebSocketHandler extends TextWebSocketHandler {

		private final ObjectMapper objectMapper = new ObjectMapper();

		@Override
		public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
			ChatMessage chatMessage = objectMapper.readValue(message.getPayload(), ChatMessage.class);
			// do something with the chatMessage
		}

		@Override
		public void afterConnectionEstablished(WebSocketSession session) throws Exception {
			// do something after a WebSocket connection is established
		}
	}
}
